<template>
  <div class="appointments-container">
    <div class="page-header">
      <div class="page-title">
        <h2>预约管理</h2>
      </div>
      <div class="page-actions">
        <a-button type="primary" @click="showNewAppointmentModal">
          <template #icon><plus-outlined /></template>
          新建预约
        </a-button>
      </div>
    </div>

    <div class="page-content">
      <!-- 日历部分 -->
      <div class="calendar-section">
        <div class="section-header">
          <h3>日历视图</h3>
          <div class="section-actions">
            <a-radio-group v-model:value="calendarView" button-style="solid" size="small">
              <a-radio-button value="month">月</a-radio-button>
              <a-radio-button value="week">周</a-radio-button>
              <a-radio-button value="day">日</a-radio-button>
            </a-radio-group>
          </div>
        </div>
        
        <a-calendar 
          :fullscreen="false" 
          @select="onCalendarSelect"
          @panelChange="onPanelChange"
        >
          <template #dateCellRender="{ current }">
            <div class="date-cell">
              <div v-if="hasAppointments(current)" class="appointment-indicator">
                <a-badge :count="getAppointmentCount(current)" :number-style="{ backgroundColor: '#1890ff' }" />
              </div>
            </div>
          </template>
        </a-calendar>
        
        <div class="calendar-legend">
          <div class="legend-item">
            <div class="legend-color" style="background-color: #1890ff;"></div>
            <span>预约</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: #52c41a;"></div>
            <span>已完成</span>
          </div>
          <div class="legend-item">
            <div class="legend-color" style="background-color: #faad14;"></div>
            <span>待确认</span>
          </div>
        </div>
      </div>

      <!-- 预约列表部分 -->
      <div class="appointments-section">
        <div class="section-header">
          <h3>{{ getDateTitle() }}</h3>
          <div class="section-actions">
            <a-input-search
              v-model:value="searchKeyword"
              placeholder="搜索患者姓名/电话"
              style="width: 250px"
              @search="handleSearch"
              allowClear
            />
            <a-select
              v-model:value="statusFilter"
              placeholder="状态筛选"
              style="width: 120px"
              allowClear
              @change="handleSearch"
            >
              <a-select-option value="pending">待确认</a-select-option>
              <a-select-option value="confirmed">已确认</a-select-option>
              <a-select-option value="completed">已完成</a-select-option>
              <a-select-option value="cancelled">已取消</a-select-option>
            </a-select>
          </div>
        </div>
        
        <a-list
          :loading="loading"
          :data-source="filteredAppointments"
          :pagination="pagination"
          item-layout="horizontal"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-list-item-meta>
                <template #title>
                  <div class="appointment-title">
                    <span>{{ item.patientName }}</span>
                    <a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
                  </div>
                </template>
                <template #description>
                  <div class="appointment-description">
                    <p><clock-circle-outlined /> {{ formatDateTime(item.appointmentTime) }}</p>
                    <p><phone-outlined /> {{ item.phone }}</p>
                    <p><medicine-box-outlined /> {{ item.treatmentType }}</p>
                    <p v-if="item.notes"><info-circle-outlined /> {{ item.notes }}</p>
                  </div>
                </template>
                <template #avatar>
                  <a-avatar :style="{ backgroundColor: getAvatarColor(item.patientName) }">
                    {{ getNameInitial(item.patientName) }}
                  </a-avatar>
                </template>
              </a-list-item-meta>
              <div class="appointment-actions">
                <a-space>
                  <a @click="viewAppointment(item)">查看</a>
                  <a @click="editAppointment(item)">编辑</a>
                  <a @click="showSendReminderModal(item)" v-if="item.status === 'confirmed'">发送提醒</a>
                  <a-dropdown>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item key="complete" v-if="item.status === 'confirmed'" @click="updateAppointmentStatus(item, 'completed')">
                          标记为已完成
                        </a-menu-item>
                        <a-menu-item key="confirm" v-if="item.status === 'pending'" @click="updateAppointmentStatus(item, 'confirmed')">
                          确认预约
                        </a-menu-item>
                        <a-menu-item key="cancel" v-if="['pending', 'confirmed'].includes(item.status)" @click="showCancelModal(item)">
                          取消预约
                        </a-menu-item>
                        <a-menu-item key="delete" @click="showDeleteModal(item)">
                          删除
                        </a-menu-item>
                      </a-menu>
                    </template>
                    <a>更多 <down-outlined /></a>
                  </a-dropdown>
                </a-space>
              </div>
            </a-list-item>
          </template>
          <template #empty>
            <div class="empty-container">
              <a-empty description="暂无预约" />
            </div>
          </template>
        </a-list>
      </div>
    </div>

    <!-- 新建/编辑预约弹窗 -->
    <a-modal
      v-model:visible="appointmentModalVisible"
      :title="modalTitle"
      @ok="formRef?.validate().then(handleAppointmentSubmit)"
      :confirmLoading="submitLoading"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="appointmentForm"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item name="patientName" label="患者姓名">
          <a-input v-model:value="appointmentForm.patientName" placeholder="请输入患者姓名" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="phone" label="联系电话">
              <a-input v-model:value="appointmentForm.phone" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="status" label="预约状态">
              <a-select v-model:value="appointmentForm.status" placeholder="请选择预约状态">
                <a-select-option value="pending">待确认</a-select-option>
                <a-select-option value="confirmed">已确认</a-select-option>
                <a-select-option value="completed">已完成</a-select-option>
                <a-select-option value="cancelled">已取消</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item name="appointmentDate" label="预约日期">
              <a-date-picker 
                v-model:value="appointmentForm.appointmentDate" 
                style="width: 100%" 
                :disabledDate="disabledDate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="appointmentTime" label="预约时间">
              <a-time-picker 
                v-model:value="appointmentForm.appointmentTime" 
                format="HH:mm" 
                style="width: 100%" 
                :minute-step="15"
                :disabledHours="disabledHours"
              />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item name="treatmentType" label="治疗类型">
          <a-select v-model:value="appointmentForm.treatmentType" placeholder="请选择治疗类型">
            <a-select-option value="初诊">初诊</a-select-option>
            <a-select-option value="复诊">复诊</a-select-option>
            <a-select-option value="正畸复查">正畸复查</a-select-option>
            <a-select-option value="洗牙">洗牙</a-select-option>
            <a-select-option value="补牙">补牙</a-select-option>
            <a-select-option value="拔牙">拔牙</a-select-option>
            <a-select-option value="根管治疗">根管治疗</a-select-option>
            <a-select-option value="牙齿美白">牙齿美白</a-select-option>
            <a-select-option value="其他">其他</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item name="doctor" label="主治医生">
          <a-select v-model:value="appointmentForm.doctor" placeholder="请选择主治医生">
            <a-select-option value="李医生">李医生</a-select-option>
            <a-select-option value="王医生">王医生</a-select-option>
            <a-select-option value="张医生">张医生</a-select-option>
            <a-select-option value="刘医生">刘医生</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item name="notes" label="备注">
          <a-textarea v-model:value="appointmentForm.notes" placeholder="请输入备注信息" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看预约详情弹窗 -->
    <a-modal
      v-model:visible="viewModalVisible"
      title="预约详情"
      :footer="null"
      width="500px"
    >
      <div class="appointment-detail" v-if="currentAppointment">
        <div class="detail-header">
          <a-avatar :size="64" :style="{ backgroundColor: getAvatarColor(currentAppointment.patientName) }">
            {{ getNameInitial(currentAppointment.patientName) }}
          </a-avatar>
          <div class="detail-title">
            <h3>{{ currentAppointment.patientName }}</h3>
            <a-tag :color="getStatusColor(currentAppointment.status)">{{ getStatusText(currentAppointment.status) }}</a-tag>
          </div>
        </div>
        
        <div class="detail-content">
          <div class="detail-item">
            <div class="item-label">预约时间</div>
            <div class="item-value">{{ formatDateTime(currentAppointment.appointmentTime) }}</div>
          </div>
          
          <div class="detail-item">
            <div class="item-label">联系电话</div>
            <div class="item-value">{{ currentAppointment.phone }}</div>
          </div>
          
          <div class="detail-item">
            <div class="item-label">治疗类型</div>
            <div class="item-value">{{ currentAppointment.treatmentType }}</div>
          </div>
          
          <div class="detail-item">
            <div class="item-label">主治医生</div>
            <div class="item-value">{{ currentAppointment.doctor }}</div>
          </div>
          
          <div class="detail-item" v-if="currentAppointment.notes">
            <div class="item-label">备注</div>
            <div class="item-value">{{ currentAppointment.notes }}</div>
          </div>
          
          <div class="detail-item">
            <div class="item-label">创建时间</div>
            <div class="item-value">{{ currentAppointment.createdAt }}</div>
          </div>
        </div>
        
        <div class="detail-actions">
          <a-space>
            <a-button type="primary" @click="editAppointment(currentAppointment)">编辑</a-button>
            <a-button v-if="currentAppointment.status === 'confirmed'" @click="showSendReminderModal(currentAppointment)">发送提醒</a-button>
            <a-button v-if="currentAppointment.status === 'confirmed'" @click="updateAppointmentStatus(currentAppointment, 'completed')">标记为已完成</a-button>
            <a-button v-if="currentAppointment.status === 'pending'" @click="updateAppointmentStatus(currentAppointment, 'confirmed')">确认预约</a-button>
            <a-button danger v-if="['pending', 'confirmed'].includes(currentAppointment.status)" @click="showCancelModal(currentAppointment)">取消预约</a-button>
          </a-space>
        </div>
      </div>
    </a-modal>

    <!-- 发送提醒弹窗 -->
    <a-modal
      v-model:visible="reminderModalVisible"
      title="发送预约提醒"
      @ok="handleSendReminder"
      :confirmLoading="reminderLoading"
    >
      <div class="reminder-content">
        <p>您将向以下患者发送预约提醒：</p>
        <p><strong>患者：</strong>{{ currentAppointment?.patientName }}</p>
        <p><strong>电话：</strong>{{ currentAppointment?.phone }}</p>
        <p><strong>预约时间：</strong>{{ formatDateTime(currentAppointment?.appointmentTime) }}</p>
        
        <a-form layout="vertical">
          <a-form-item label="提醒方式">
            <a-checkbox-group v-model:value="reminderMethods">
              <a-checkbox value="sms">短信</a-checkbox>
              <a-checkbox value="phone">电话</a-checkbox>
              <a-checkbox value="wechat">微信</a-checkbox>
            </a-checkbox-group>
          </a-form-item>
          
          <a-form-item label="提醒内容">
            <a-textarea 
              v-model:value="reminderContent" 
              :rows="4" 
              :placeholder="defaultReminderContent"
            />
          </a-form-item>
        </a-form>
        
        <div class="reminder-message">
          <p><info-circle-outlined /> 提示：</p>
          <p>1. 短信提醒将发送到患者登记的手机号码</p>
          <p>2. 微信提醒需要患者已关注诊所公众号</p>
        </div>
      </div>
    </a-modal>

    <!-- 取消预约弹窗 -->
    <a-modal
      v-model:visible="cancelModalVisible"
      title="取消预约"
      @ok="handleCancelAppointment"
      :confirmLoading="cancelLoading"
    >
      <div class="cancel-content">
        <p>您确定要取消以下预约吗？</p>
        <p><strong>患者：</strong>{{ currentAppointment?.patientName }}</p>
        <p><strong>预约时间：</strong>{{ formatDateTime(currentAppointment?.appointmentTime) }}</p>
        
        <a-form layout="vertical">
          <a-form-item label="取消原因" name="cancelReason">
            <a-select v-model:value="cancelReason" placeholder="请选择取消原因">
              <a-select-option value="患者要求">患者要求</a-select-option>
              <a-select-option value="医生时间冲突">医生时间冲突</a-select-option>
              <a-select-option value="诊所设备维护">诊所设备维护</a-select-option>
              <a-select-option value="其他原因">其他原因</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="备注" v-if="cancelReason === '其他原因'">
            <a-textarea v-model:value="cancelNote" :rows="3" placeholder="请输入取消原因" />
          </a-form-item>
          
          <a-form-item label="是否通知患者">
            <a-switch v-model:checked="notifyPatient" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 删除预约确认弹窗 -->
    <a-modal
      v-model:visible="deleteModalVisible"
      title="删除预约"
      @ok="handleDeleteAppointment"
      :confirmLoading="deleteLoading"
      okText="删除"
      okType="danger"
    >
      <p>您确定要删除 <strong>{{ currentAppointment?.patientName }}</strong> 的预约记录吗？</p>
      <p>此操作不可恢复，请谨慎操作。</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { 
  UserOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  PhoneOutlined,
  MedicineBoxOutlined,
  InfoCircleOutlined,
  DownOutlined,
  CalendarOutlined,
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons-vue'

// 表单引用
const formRef = ref(null)
const submitLoading = ref(false)

// 日历视图
const calendarView = ref('month')
const selectedDate = ref(dayjs())

// 搜索和筛选
const searchKeyword = ref('')
const statusFilter = ref(null)
const loading = ref(false)

// 模态框状态
const appointmentModalVisible = ref(false)
const viewModalVisible = ref(false)
const reminderModalVisible = ref(false)
const cancelModalVisible = ref(false)
const deleteModalVisible = ref(false)
const modalTitle = ref('新建预约')
const currentAppointment = ref(null)

// 提醒相关
const reminderMethods = ref(['sms'])
const reminderContent = ref('')
const reminderLoading = ref(false)
const defaultReminderContent = computed(() => {
  if (!currentAppointment.value) return ''
  
  return `尊敬的${currentAppointment.value.patientName}，提醒您：您预约的${formatDateTime(currentAppointment.value.appointmentTime)}${currentAppointment.value.treatmentType}即将开始，请准时到诊。如需变更，请提前联系我们。`
})

// 取消相关
const cancelReason = ref('')
const cancelNote = ref('')
const notifyPatient = ref(true)
const cancelLoading = ref(false)

// 删除相关
const deleteLoading = ref(false)

// 预约表单数据
const appointmentForm = reactive({
  patientName: '',
  phone: '',
  status: 'pending',
  appointmentDate: null,
  appointmentTime: null,
  treatmentType: '',
  doctor: '',
  notes: ''
})

// 表单验证规则
const rules = {
  patientName: [
    { required: true, message: '请输入患者姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择预约状态', trigger: 'change' }
  ],
  appointmentDate: [
    { required: true, message: '请选择预约日期', trigger: 'change', type: 'object' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change', type: 'object' }
  ],
  treatmentType: [
    { required: true, message: '请选择治疗类型', trigger: 'change' }
  ],
  doctor: [
    { required: true, message: '请选择主治医生', trigger: 'change' }
  ]
}

// 分页设置
const pagination = reactive({
  pageSize: 10,
  current: 1,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  pageSizeOptions: ['5', '10', '20', '50']
})

// 模拟预约数据
const appointments = ref([
  {
    id: 'A20240301001',
    patientName: '张三',
    phone: '13800138000',
    status: 'confirmed',
    appointmentTime: dayjs().add(1, 'day').hour(10).minute(0).second(0),
    treatmentType: '正畸复查',
    doctor: '李医生',
    notes: '患者需要更换新的橡皮筋',
    createdAt: '2024-03-01 09:15:00'
  },
  {
    id: 'A20240302002',
    patientName: '李四',
    phone: '13900139000',
    status: 'pending',
    appointmentTime: dayjs().add(2, 'day').hour(14).minute(30).second(0),
    treatmentType: '初诊',
    doctor: '王医生',
    notes: '',
    createdAt: '2024-03-02 11:20:00'
  },
  {
    id: 'A20240303003',
    patientName: '王五',
    phone: '13700137000',
    status: 'completed',
    appointmentTime: dayjs().subtract(1, 'day').hour(16).minute(0).second(0),
    treatmentType: '洗牙',
    doctor: '张医生',
    notes: '患者有轻微牙龈出血情况',
    createdAt: '2024-03-03 08:45:00'
  },
  {
    id: 'A20240304004',
    patientName: '赵六',
    phone: '13600136000',
    status: 'cancelled',
    appointmentTime: dayjs().hour(9).minute(0).second(0),
    treatmentType: '补牙',
    doctor: '刘医生',
    notes: '患者临时有事取消',
    createdAt: '2024-03-04 14:30:00',
    cancelReason: '患者要求'
  },
  {
    id: 'A20240305005',
    patientName: '钱七',
    phone: '13500135000',
    status: 'confirmed',
    appointmentTime: dayjs().add(3, 'day').hour(11).minute(30).second(0),
    treatmentType: '根管治疗',
    doctor: '李医生',
    notes: '',
    createdAt: '2024-03-05 16:10:00'
  }
])

// 根据日期和搜索条件过滤预约
const filteredAppointments = computed(() => {
  let result = [...appointments.value]
  
  // 按日期过滤
  if (selectedDate.value) {
    const startOfDay = selectedDate.value.startOf('day')
    const endOfDay = selectedDate.value.endOf('day')
    
    result = result.filter(item => {
      const appointmentDate = dayjs(item.appointmentTime)
      return appointmentDate.isAfter(startOfDay) && appointmentDate.isBefore(endOfDay)
    })
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item => 
      item.patientName.toLowerCase().includes(keyword) || 
      item.phone.includes(keyword)
    )
  }
  
  // 按状态过滤
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value)
  }
  
  // 更新分页总数
  pagination.total = result.length
  
  return result
})

// 获取日期标题
const getDateTitle = () => {
  if (!selectedDate.value) return '今日预约'
  
  const today = dayjs()
  const selected = selectedDate.value
  
  if (selected.isSame(today, 'day')) {
    return '今日预约'
  } else if (selected.isSame(today.add(1, 'day'), 'day')) {
    return '明日预约'
  } else if (selected.isSame(today.subtract(1, 'day'), 'day')) {
    return '昨日预约'
  } else {
    return `${selected.format('YYYY年MM月DD日')}预约`
  }
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    pending: 'orange',
    confirmed: 'blue',
    completed: 'green',
    cancelled: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    pending: '待确认',
    confirmed: '已确认',
    completed: '已完成',
    cancelled: '已取消'
  }
  return textMap[status] || '未知'
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return dayjs(datetime).format('YYYY-MM-DD HH:mm')
}

// 获取头像颜色
const getAvatarColor = (name) => {
  if (!name) return '#1890ff'
  
  const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96']
  const charCode = name.charCodeAt(0)
  return colors[charCode % colors.length]
}

// 获取姓名首字母
const getNameInitial = (name) => {
  if (!name) return ''
  return name.charAt(0)
}

// 判断日期是否有预约
const hasAppointments = (date) => {
  return getAppointmentCount(date) > 0
}

// 获取日期预约数量
const getAppointmentCount = (date) => {
  if (!date) return 0
  
  const startOfDay = dayjs(date).startOf('day')
  const endOfDay = dayjs(date).endOf('day')
  
  return appointments.value.filter(item => {
    const appointmentDate = dayjs(item.appointmentTime)
    return appointmentDate.isAfter(startOfDay) && appointmentDate.isBefore(endOfDay)
  }).length
}

// 日历选择处理
const onCalendarSelect = (date) => {
  selectedDate.value = dayjs(date)
}

// 日历面板变化处理
const onPanelChange = (date) => {
  // 只改变月份，不改变选中日期
}

// 搜索处理
const handleSearch = () => {
  // 搜索已经通过计算属性实现
}

// 禁用过去的日期
const disabledDate = (current) => {
  return current && current < dayjs().startOf('day')
}

// 禁用非工作时间
const disabledHours = () => {
  return Array.from({ length: 24 }).map((_, i) => i).filter(h => h < 8 || h > 18)
}

// 显示新建预约弹窗
const showNewAppointmentModal = () => {
  modalTitle.value = '新建预约'
  Object.keys(appointmentForm).forEach(key => {
    if (key === 'status') {
      appointmentForm[key] = 'pending'
    } else {
      appointmentForm[key] = null
    }
  })
  
  // 默认设置为当前选中日期
  if (selectedDate.value) {
    appointmentForm.appointmentDate = selectedDate.value
    appointmentForm.appointmentTime = dayjs().hour(9).minute(0).second(0)
  }
  
  appointmentModalVisible.value = true
}

// 查看预约
const viewAppointment = (record) => {
  currentAppointment.value = { ...record }
  viewModalVisible.value = true
}

// 编辑预约
const editAppointment = (record) => {
  modalTitle.value = '编辑预约'
  currentAppointment.value = { ...record }
  
  // 设置表单值
  appointmentForm.patientName = record.patientName
  appointmentForm.phone = record.phone
  appointmentForm.status = record.status
  appointmentForm.appointmentDate = dayjs(record.appointmentTime)
  appointmentForm.appointmentTime = dayjs(record.appointmentTime)
  appointmentForm.treatmentType = record.treatmentType
  appointmentForm.doctor = record.doctor
  appointmentForm.notes = record.notes
  
  appointmentModalVisible.value = true
  
  // 如果是从详情页编辑，关闭详情页
  if (viewModalVisible.value) {
    viewModalVisible.value = false
  }
}

// 显示发送提醒弹窗
const showSendReminderModal = (record) => {
  currentAppointment.value = { ...record }
  reminderMethods.value = ['sms']
  reminderContent.value = ''
  reminderModalVisible.value = true
}

// 处理发送提醒
const handleSendReminder = () => {
  if (reminderMethods.value.length === 0) {
    message.warning('请至少选择一种提醒方式')
    return
  }
  
  reminderLoading.value = true
  
  // 模拟发送提醒
  setTimeout(() => {
    reminderLoading.value = false
    reminderModalVisible.value = false
    message.success('提醒已发送')
  }, 1000)
}

// 显示取消预约弹窗
const showCancelModal = (record) => {
  currentAppointment.value = { ...record }
  cancelReason.value = ''
  cancelNote.value = ''
  notifyPatient.value = true
  cancelModalVisible.value = true
}

// 处理取消预约
const handleCancelAppointment = () => {
  if (!cancelReason.value) {
    message.warning('请选择取消原因')
    return
  }
  
  if (cancelReason.value === '其他原因' && !cancelNote.value) {
    message.warning('请输入取消原因')
    return
  }
  
  cancelLoading.value = true
  
  // 模拟取消预约
  setTimeout(() => {
    // 更新预约状态
    const index = appointments.value.findIndex(item => item.id === currentAppointment.value.id)
    if (index !== -1) {
      appointments.value[index].status = 'cancelled'
      appointments.value[index].cancelReason = cancelReason.value
      if (cancelReason.value === '其他原因') {
        appointments.value[index].cancelNote = cancelNote.value
      }
    }
    
    cancelLoading.value = false
    cancelModalVisible.value = false
    message.success('预约已取消')
    
    // 如果是从详情页取消，关闭详情页
    if (viewModalVisible.value) {
      viewModalVisible.value = false
    }
  }, 1000)
}

// 显示删除预约弹窗
const showDeleteModal = (record) => {
  currentAppointment.value = { ...record }
  deleteModalVisible.value = true
}

// 处理删除预约
const handleDeleteAppointment = () => {
  deleteLoading.value = true
  
  // 模拟删除预约
  setTimeout(() => {
    // 从列表中删除
    appointments.value = appointments.value.filter(item => item.id !== currentAppointment.value.id)
    
    deleteLoading.value = false
    deleteModalVisible.value = false
    message.success('预约已删除')
    
    // 如果是从详情页删除，关闭详情页
    if (viewModalVisible.value) {
      viewModalVisible.value = false
    }
  }, 1000)
}

// 更新预约状态
const updateAppointmentStatus = (record, status) => {
  // 更新预约状态
  const index = appointments.value.findIndex(item => item.id === record.id)
  if (index !== -1) {
    appointments.value[index].status = status
    message.success(`预约已${getStatusText(status)}`)
    
    // 如果是从详情页更新，更新详情页数据
    if (viewModalVisible.value && currentAppointment.value?.id === record.id) {
      currentAppointment.value.status = status
    }
  }
}

// 处理预约表单提交
const handleAppointmentSubmit = () => {
  submitLoading.value = true
  
  // 合并日期和时间
  const appointmentDateTime = dayjs(appointmentForm.appointmentDate)
    .hour(appointmentForm.appointmentTime.hour())
    .minute(appointmentForm.appointmentTime.minute())
    .second(0)
  
  // 模拟提交
  setTimeout(() => {
    const newAppointment = {
      id: modalTitle.value === '新建预约' 
        ? `A${dayjs().format('YYYYMMDDHHmmss')}` 
        : currentAppointment.value.id,
      patientName: appointmentForm.patientName,
      phone: appointmentForm.phone,
      status: appointmentForm.status,
      appointmentTime: appointmentDateTime,
      treatmentType: appointmentForm.treatmentType,
      doctor: appointmentForm.doctor,
      notes: appointmentForm.notes,
      createdAt: modalTitle.value === '新建预约' 
        ? dayjs().format('YYYY-MM-DD HH:mm:ss')
        : currentAppointment.value.createdAt
    }
    
    if (modalTitle.value === '新建预约') {
      // 新增
      appointments.value.unshift(newAppointment)
      message.success('预约创建成功')
    } else {
      // 编辑
      const index = appointments.value.findIndex(item => item.id === currentAppointment.value.id)
      if (index !== -1) {
        appointments.value[index] = newAppointment
      }
      message.success('预约更新成功')
    }
    
    appointmentModalVisible.value = false
    submitLoading.value = false
  }, 1000)
}

// 初始化加载数据
onMounted(() => {
  // 设置默认选中今天
  selectedDate.value = dayjs()
})
</script>

<style scoped>
.appointments-container {
  width: 100%;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.page-title h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.page-content {
  display: grid;
  grid-template-columns: 1fr 1.5fr;
  gap: 24px;
}

.calendar-section,
.appointments-section {
  background-color: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.section-actions {
  display: flex;
  gap: 8px;
}

/* 日历样式 */
.date-cell {
  position: relative;
  height: 100%;
  width: 100%;
}

.appointment-indicator {
  position: absolute;
  bottom: 0;
  right: 0;
}

.calendar-legend {
  display: flex;
  gap: 16px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

/* 预约列表样式 */
.appointment-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.appointment-description {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.appointment-description p {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 4px;
  color: rgba(0, 0, 0, 0.65);
}

.appointment-actions {
  display: flex;
  justify-content: flex-end;
}

.empty-container {
  padding: 32px 0;
}

/* 预约详情样式 */
.appointment-detail {
  padding: 16px;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.detail-title {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.detail-content {
  margin-bottom: 24px;
}

.detail-item {
  display: flex;
  margin-bottom: 16px;
}

.item-label {
  width: 100px;
  color: rgba(0, 0, 0, 0.65);
}

.item-value {
  flex: 1;
  color: rgba(0, 0, 0, 0.85);
}

.detail-actions {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

/* 提醒弹窗样式 */
.reminder-content,
.cancel-content {
  padding: 8px;
}

.reminder-message {
  margin-top: 16px;
  padding: 12px;
  background-color: #f6f6f6;
  border-radius: 4px;
}

.reminder-message p {
  margin: 4px 0;
  color: rgba(0, 0, 0, 0.65);
}

/* 响应式布局 */
@media (max-width: 992px) {
  .page-content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 576px) {
  .appointments-container {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .appointment-description {
    grid-template-columns: 1fr;
  }
}
</style>